<?php
/**
* 数据库Session
*/
class ms_db_session
{
	public static $_this = null;

	public static function start($return_class = true)
	{
		$handler = new hp_dbsession;
		session_set_save_handler(
			array($handler, 'open'),
			array($handler, 'close'),
			array($handler, 'read'),
			array($handler, 'write'),
			array($handler, 'destroy'),
			array($handler, 'gc')
		);

		// 下面这行代码可以防止使用对象作为会话保存管理器时可能引发的非预期行为
		register_shutdown_function('session_write_close');
		ini_set("session.cookie_domain",G('cookiedomain'));
		session_start();

		//返回一个封装的session操作类
		if($return_class) {
			if(!static::$_this) static::$_this = new self;
			return static::$_this;
		}
	}

	//从session中设置自定义变量
	public function __set($key, $value)
	{
		if($value === null) {
			$this->clear($key);
		} else {
			$_SESSION[$key] = $value;
		}
	}

	//从session中获取自定义变量
	public function __get($key)
	{
		if(isset($_SESSION[$key])) {
			return $_SESSION[$key];
		} else {
			return null;
		}
	}

	public function clear($key)
	{
		if(isset($_SESSION[$key])) unset($_SESSION[$key]);
	}

	//获取全部session保存的自定义参数
	public function fetch_all()
	{
		return $_SESSION;
	}

	//获取session_id
	public function get_id()
	{
		return session_id();
	}

	//获取sesion表主键ID
	public function get_keyid()
	{
		return G('loader')->model('dbsession')->my_table()->select('id')
			->where('uniq', $this->get_id())->get_value();
	}

	//设置session_id关联的UID
	public function set_uid($uid)
	{
		return true;
	}

	//获取在线人数，基于session数量进行统计
	public function get_online_total()
	{
		// $cache = _G('dbcache')->fetch(self::CACHE_KEY_ONLINE);
		// if($cache) {
		// 	list($count, $total_time) = explode("\t", $cache);
		// 	//10分钟统计一次
		// 	if(600 > $this->timestamp - $total_time && $this->timestamp > $total_time) return $count;
		// }
		// //过滤超时的session
		// $time = $this->timestamp - $this->expiry_time;
		// $count = G('loader')->model('dbsession')->my_table()->where_more('last_time', $time)->count();
		// _G('dbcache')->write(self::CACHE_KEY_ONLINE, "{$count}\t{$this->timestamp}");

		return 0;
	}

} 

/** end **/